package controller

import (
	"errors"
	"fmt"
	"github.com/e421083458/gorm"
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
	"rock/customer/dto"
	"rock/customer/initParam"
	"rock/customer/middleware"
	"rock/customer/modules/cacheMap"
	"strings"
	"time"
)

// @Summary 加入群组
// @Description
// @Tags 群组成员
// @ID /joingroup
// @Accept  json
// @Produce  json
// @Param polygon body dto.Groups true "body"
// @Success 200 {object} middleware.Response{} "success"
// @Router /joingroup [post]
func (g *GroupController) joinGroup(router *gin.Context) {
	params := &dto.Groups{}
	if err := params.BindingParams(router); err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	// 发送一个邀请通知的方式
	//发送入群提示语
	groupMember, err := groupService.GroupMember(router, BusinessDB, params.GroupId)
	if err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
			return
		}
	}
	arr := make([]string, 0)
	for _, v := range groupMember {
		arr = append(arr, gconv.String(v.UserID))
	}
	invitationMember := make([]string, 0)
	invitationMemberCache := cacheMap.InvitationMember.Get(params.GroupId)
	if invitationMemberCache != nil {
		invitationMember = invitationMemberCache.([]string)
	}
	for _, member := range params.GroupMembers {
		if gstr.InArray(arr, gconv.String(member.UserId)) {
			continue
		}
		invitationMember = append(invitationMember, gconv.String(member.UserId))
		cacheMap.InvitationMemberDetail.Set(params.GroupId+"_"+gconv.String(member.UserId), time.Now().Add(initParam.InvitationTimeOut).Unix())
		//发送一个邀请通知的方式
		err = send(dto.Group{
			GroupId: params.GroupId,
			//前端缺少参数 param.UserId
			UserId:      gconv.String(params.UserId),
			OtherUserId: gconv.String(member.UserId),
			MsgType:     7, //
		})
		if err != nil {
			middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
			return
		}
	}
	if len(invitationMember) > 0 {
		cacheMap.InvitationMember.Set(params.GroupId, invitationMember)
	}
	//发送正在邀请客服提示语
	err = send(dto.Group{
		GroupId: params.GroupId,
		MsgType: 10, //
	})
	if err != nil {
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
		return
	}
	middleware.ResponseSuccess(router, gin.H{"msg": initParam.DealSuccessText})
}

// @Summary 退出群组,踢人
// @Description 传参只需要传UserId，GroupId（踢多人user_id用,隔开）
// @Tags 群组成员
// @ID /quitgroup
// @Accept  json
// @Produce  json
// @Param polygon body dto.Group true "body"
// @Success 200 {object} middleware.Response{} "success"
// @Router /quitgroup [post]
func (g *GroupController) quitGroup(router *gin.Context) {
	params := &dto.Group{}
	if err := params.BindingParams(router); err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	//
	updateRedis(router, params.GroupId)
	//
	groupMemberCs, err := groupService.GroupMemberCs(router, BusinessDB, params.GroupId)
	if err != nil {
		if err.Error() == initParam.DataIsNotExist {
			middleware.ResponseError(router, middleware.DATA_NOT_EXIST, err)
			return
		}
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
		return
	}
	isQuit := 0
	canQuitUserId := make([]string, 0)

	for _, member := range groupMemberCs {
		if params.QuitType > 2 {
			if member.MemberType > 1 {
				canQuitUserId = append(canQuitUserId, gconv.String(member.UserID))
			}
		} else {
			if isQuit == 1 {
				canQuitUserId = append(canQuitUserId, gconv.String(member.UserID))
			}
			if member.MemberType > 1 {
				isQuit = 1
			}
		}
	}
	//
	quitUserId := ""
	cacheQuitUserId := make([]string, 0)
	quitMemberName := ""
	//
	transaction := BusinessDB.Begin()
	if strings.Contains(params.UserId, ",") {
		userIds := strings.Split(params.UserId, ",")
		for _, id := range userIds {
			if !gstr.InArray(canQuitUserId, id) {
				continue
			}
			if len(quitUserId) > 0 {
				quitUserId = quitUserId + "&"
			}
			//quitUserId = quitUserId + "userId=" + id
			quitUserId = quitUserId + "userId=" + initParam.CsTarget + id
			err = groupService.DeleteGroupMember(router, transaction, params.GroupId, id)
			if err != nil {
				Rollback(router.Request.URL.Path, transaction, err)
			}
			cacheQuitUserId = append(cacheQuitUserId, id)
			for _, member := range groupMemberCs {
				if id == gconv.String(member.UserID) {
					quitMemberName = quitMemberName + member.MemberName + ","
				}
			}
		}
		if err != nil {
			middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
			return
		}
	} else {
		if !gstr.InArray(canQuitUserId, params.UserId) {
			err = groupService.UpdateGroupState(router, transaction, params.GroupId, 2)
			if err != nil {
				Rollback(router.Request.URL.Path, transaction, err)
				middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
				return
			}
			transaction.Commit()
			middleware.ResponseSuccess(router, gin.H{"msg": initParam.DealSuccessText})
			return
		}
		//quitUserId = "userId=" + params.UserId
		quitUserId = "userId=" + initParam.CsTarget + params.UserId
		err := groupService.DeleteGroupMember(router, transaction, params.GroupId, params.UserId)
		if err != nil {
			Rollback(router.Request.URL.Path, transaction, err)
			middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
			return
		}
		cacheQuitUserId = append(cacheQuitUserId, params.UserId)
		for _, member := range groupMemberCs {
			if params.UserId == gconv.String(member.UserID) {
				quitMemberName = quitMemberName + member.MemberName + ","
			}
		}
	}
	transaction.Commit()
	//
	err = quitGroupTransaction(router, params, groupMemberCs, canQuitUserId, quitUserId, cacheQuitUserId, quitMemberName)
	if err != nil {
		if err.Error() == "LOGICAL SUCCESS" {
			middleware.ResponseSuccess(router, gin.H{"msg": initParam.DealSuccessText})
			return
		}
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
		return
	}
	//
	if params.QuitType == 1 {
		err = send(dto.Group{
			MsgType: 19,
			GroupId: params.GroupId,
			UserId:  params.UserId,
		})
		if err != nil {
			middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
			return
		}
	}
	if params.QuitType == 2 {
		err = send(dto.Group{
			MsgType: 20,
			GroupId: params.GroupId,
			Msg:     quitMemberName[0 : len(quitMemberName)-1],
			UserId:  params.UserId,
		})
		if err != nil {
			middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
			return
		}
	}
	if len(cacheQuitUserId) == 0 {
		err = groupService.UpdateGroupState(router, InstanceDB, params.GroupId, 2)
		if err != nil {
			middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
			return
		}
		middleware.ResponseSuccess(router, gin.H{"msg": initParam.DealSuccessText})
		return
	}
	clearGroupMemberCache(params.GroupId, cacheQuitUserId)
	rcParam := fmt.Sprintf("%s&groupId=%s", quitUserId, params.GroupId)
	err = quitGroupRonCloud(rcParam)
	if err != nil {
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
		return
	}
	//清空群成员缓存
	//cacheMap.GroupMember.Remove(params.GroupId)
	middleware.ResponseSuccess(router, gin.H{"msg": initParam.DealSuccessText})
}

// @Summary 群组成员查询
// @Description 传参只需要传GroupId
// @Tags 群组成员
// @ID /querygroupmember
// @Accept  json
// @Produce  json
// @Param polygon body dto.Group true "body"
// @Success 200 {object} middleware.Response{data=[]dto.Groups} "success"
// @Router /querygroupmember [post]
func (g *GroupController) queryGroupMember(router *gin.Context) {
	params := &dto.Group{}
	if err := params.BindingParams(router); err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	//
	groupCache := getGroupMsg(router, params.GroupId)
	if groupCache.GroupID == "" {
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, errors.New(initParam.ErrorGroupCache))
		return
	}
	groupMember, err := groupService.GroupMember(router, BusinessDB, params.GroupId)
	if err != nil {
		dealRequestError(router, err)
		return
	}
	members := make([]dto.GroupMembers, 0)
	customerMembers := dto.GroupMembers{}
	isQuit := 0
	for _, member := range groupMember {
		if member.MemberType == 0 {
			if !strings.Contains(member.Avatar, "http") {
				member.Avatar = initParam.CAvatar
			}
			customerMembers = dto.GroupMembers{
				UserName:   member.MemberName,
				Avatar:     member.Avatar,
				UserType:   member.MemberType,
				UserId:     member.UserID,
				IsQuit:     isQuit,
				MemberType: member.MemberType,
			}
		} else {
			model := dto.GroupMembers{
				UserName: member.MemberName,
				//Avatar:   member.Avatar,
				Avatar:     initParam.FAEAvatar,
				UserType:   member.MemberType,
				UserId:     member.UserID,
				IsQuit:     isQuit,
				MemberType: member.MemberType,
			}
			members = append(members, model)
		}
		if member.MemberType > 1 {
			isQuit = 1
		}
	}
	if customerMembers.UserName != "" {
		members = append(members, customerMembers)
	}
	responseData := dto.Groups{
		GroupName:    groupCache.Name,
		GroupId:      groupCache.GroupID,
		GroupMembers: members,
	}
	middleware.ResponseSuccess(router, responseData)
}

// @Summary 查询用户所在群组
// @Description 传参只需要传UserId
// @Tags 群组成员
// @ID /queryjoingroup
// @Accept  json
// @Produce  json
// @Param polygon body dto.Group true "body"
// @Success 200 {object} middleware.Response{data=[]dto.GroupRongCloudInfo} "success"
// @Router /queryjoingroup [post]
func (g *GroupController) queryUserJoinGroup(router *gin.Context) {
	params := &dto.Group{}
	if err := params.BindingParams(router); err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	//
	userId := params.UserId
	if params.IsCustomerClient == 1 {
		userId = initParam.CTarget + userId
	} else {
		userId = initParam.CsTarget + userId
	}
	rcParam := fmt.Sprintf("userId=%s", userId)
	rcReq, err := queryRonGroup(rcParam)
	if err != nil {
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
		return
	}
	//
	groupIds := make([]string, 0)
	for _, model := range rcReq.Groups {
		groupIds = append(groupIds, model.Id)
	}
	//
	responseData, err := rcGroupInDb(router, params, groupIds)
	if err != nil {
		middleware.ResponseSuccess(router, responseData)
		return
	}
	middleware.ResponseSuccess(router, responseData)
}

// @Summary 点击查看更多消息
// @Description
// @Tags 会话
// @ID /changebrowsestatus
// @Accept  json
// @Produce  json
// @Param polygon body dto.Group true "body"
// @Success 200 {object} middleware.Response{} "success"
// @Router /changebrowsestatus [post]
func (g *GroupController) changeBrowseStatus(router *gin.Context) {
	params := &dto.Group{}
	if err := params.BindingParams(router); err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	err := addRedis(router, params.IsBrowseCurrentMsg, initParam.BrowseCurrentPrefix + params.GroupId)
	if err != nil {
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
		return
	}
	middleware.ResponseSuccess(router, gin.H{"msg": initParam.DealSuccessText})
}
